<?php

namespace Common;

/**
 * OSS处理类
 *
 * @package    modules
 * @subpackage Common
 * @author     fuxiang <892576@gmail.com>
 *
 * $Id$
 */
use OSS\OssClient;
use OSS\Core\OssException;

ini_set('memory_limit', '1024M');

class Oss
{
    /**
     * 日志路径定义
     */
    const LOG_FAIL_PATH = 'Common/OSS/Fail';

    private function __construct()
    {
    }

    public static function getOssClient()
    {
        $oss = loadconf('oss/oss');
        $accessKeyId = $oss['accessKeyId'];
        $accessKeySecret = $oss['accessSecret'];
        $endpoint = $oss['endPoint'];
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        $ossClient->setTimeout(3600 /* seconds */);
        $ossClient->setConnectTimeout(10 /* seconds */);

        return $ossClient;
    }

    /**
     * 上传单个文件至OSS
     *
     * @param string $path     OSS服务器上路径及文件名
     * @param string $filePath 本地文件路径和文件名
     * @param string $bucket   OSS区块名称
     *
     * @return bool
     *
     */
    public static function PutFile($path, $filePath, $bucket)
    {
        $ossClient = self::getOssClient();

        debug_log($bucket);

        try {
            $res = $ossClient->uploadFile($bucket, $path, $filePath);
        } catch (OssException $e) {
            $exception = $e->getMessage();
            runtime_log(self::LOG_FAIL_PATH,
                __METHOD__ . "files: {$filePath}, path: [" . $path . "], exception: {$exception} @ " . date('Y-m-d H:i:s'));
        }

        if ($res['info']['http_code']) {
            return true;
        }

        return false;
    }

    /**
     * 上传单个文件至OSS
     *
     * @param string $path    OSS服务器上路径及文件名
     * @param string $content 本地文件路径和文件名
     * @param string $bucket  OSS区块名称
     * @return bool
     *
     */
    public static function SaveFile($path, $content, $bucket)
    {
        $ossClient = self::getOssClient();
        debug_log($bucket);
        try {
            $res = $ossClient->putObject($bucket, $path, $content);
        } catch (OssException $e) {
            $exception = $e->getMessage();
            runtime_log(self::LOG_FAIL_PATH,
                __METHOD__ . " path: [" . $path . "], exception: {$exception} @ " . date('Y-m-d H:i:s'));
        }
        if ($res['info']['http_code']) {
            return true;
        }

        return false;
    }

}
